import md5 from "js-md5";
import { useState } from "react";
import { Button, Form, Input, message } from "antd";
import { useNavigate } from "react-router-dom";
import { Login } from "@/api/interface";
import { loginApi } from "@/api/modules/login";
import { HOME_URL } from "@/config/config";
import { connect } from "react-redux";
import { setToken } from "@/redux/modules/global/action";
import { setTabsList } from "@/redux/modules/tabs/action";
// import { UserOutlined, LockOutlined } from "@ant-design/icons";

const LoginForm = (props: any) => {
	const { setToken, setTabsList } = props;
	const navigate = useNavigate();
	const [form] = Form.useForm();
	const [loading, setLoading] = useState<boolean>(false);

	// 登录
	const onFinish = async (loginForm: Login.ReqLoginForm) => {
		try {
			setLoading(true);
			console.log("开始登录，用户名:", loginForm.username);
			loginForm.password = md5(loginForm.password);
			console.log("密码已加密");

			const result = await loginApi(loginForm);
			console.log("登录API返回结果:", result);

			const token = result?.access_token || result?.data?.access_token;
			console.log("提取的token:", token);

			if (!token) {
				throw new Error("未获取到有效的token");
			}

			setToken(token);
			setTabsList([]);
			message.success("登录成功！");
			console.log("准备跳转到:", HOME_URL);
			navigate(HOME_URL);
		} catch (error: any) {
			console.error("登录失败:", error);
			message.error(error?.response?.data?.msg || error?.message || "登录失败，请检查用户名和密码");
		} finally {
			setLoading(false);
		}
	};

	const onFinishFailed = (errorInfo: any) => {
		console.log("Failed:", errorInfo);
	};

	return (
		<Form
			form={form}
			name="basic"
			labelCol={{ span: 5 }}
			initialValues={{ remember: true }}
			onFinish={onFinish}
			onFinishFailed={onFinishFailed}
			size="large"
			autoComplete="off"
			className="border rounded-lg p-6"
		>
			<Form.Item name="username" rules={[{ required: true, message: "请输入用户名" }]} className="h-[60px] mb-0" label="用户名：">
				<Input placeholder="请输入用户名 admin / user" className="text-sm" />
			</Form.Item>
			<Form.Item name="password" rules={[{ required: true, message: "请输入密码" }]} className="h-[60px] mb-0" label="登录密码：">
				<Input.Password autoComplete="new-password" placeholder="请输入登录密码 123456" className="text-sm" />
			</Form.Item>
			<Form.Item className="w-full mt-2.5 whitespace-nowrap">
				<Button
					htmlType="submit"
					loading={loading}
					className="w-full h-14 text-white font-medium mt-4"
					style={{
						background: "linear-gradient(135deg, #0997F6 0%, #045EE9 100%)",
						border: "none",
						fontSize: "16px",
						borderRadius: "4px",
						fontWeight: "bold",
						color: "#fff"
					}}
				>
					登录
				</Button>
			</Form.Item>
		</Form>
	);
};

const mapDispatchToProps = { setToken, setTabsList };
export default connect(null, mapDispatchToProps)(LoginForm);
